
package com.xgry.bpm.api.base.beeper.controller;

import com.alibaba.fastjson.JSONObject;
import com.xgry.bpm.api.base.beeper.entity.Beeper;
import com.xgry.bpm.api.base.beeper.service.BeeperService;
import com.xgry.bpm.api.base.userInfo.entity.UserInfo;
import com.xgry.bpm.common.utils.Result;;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * <p>
    *  前端控制器
    * </p>
 *
 * @author adrian
 * @since 2020-07-08
 * @version v1.0
 */
@RestController
@RequestMapping("/beeper")
public class BeeperController {

    @Autowired
    private BeeperService beeperService;

    /**
     * 查询分页数据
     */
    @ApiOperation(value = "查询分页数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageIndex", value = "查询第几页", paramType = "query", required = true, dataType = "int"),
        @ApiImplicitParam(name = "pageSize", value = "每页多少条", paramType = "query", required = true, dataType = "int"),
        @ApiImplicitParam(name = "beeper", value = "客户查询参数", paramType = "query", required = false, dataType = "object")
    })
    @RequestMapping(value = "/getBeeperListForPage", method= RequestMethod.POST)
    public Result getBeeperListForPage(@RequestParam(name = "pageIndex", defaultValue = "1") int pageIndex,@RequestParam(name = "pageSize", defaultValue = "5") int pageSize , Beeper beeper){
        return Result.convertIpageToSuccess(beeperService.page(new Page<>(pageIndex,pageSize),new QueryWrapper<Beeper>(){{
            this.orderByDesc("pk_id");
            this.setEntity(beeper);
        }}));
    }


    /**
    * 查询list数据
    */
    @ApiOperation(value = "查询list数据")
    @ApiImplicitParam(name = "查询数据", value = "查询数据", paramType = "query", required = false, dataType = "object")
    @RequestMapping(value = "/getBeeperList", method= RequestMethod.POST)
    public Result getBeeperList(Beeper beeper){
        return Result.success(HttpStatus.OK.getReasonPhrase(),beeperService.list(new QueryWrapper<Beeper>(){{
            this.orderByAsc("pk_id");
            this.setEntity(beeper);
        }}));
    }



    /**
     * 新增/修改通知公告
     */
    @ApiOperation(value = "新增数据")
    @ApiImplicitParam(name = "beeperjson", value = "新增数据json", paramType = "query", required = true, dataType = "String")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public Result addBeeper(@RequestBody Beeper beeper){

        if (null == beeper) {
            return Result.fail("Obj is null!");
        }

        if (beeperService.save(beeper)) {
            return Result.success();
        }

        return Result.fail();
    }

    /**
     * 删除通知公告
     * */
    @RequestMapping(value = "/delete.do",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public String delete(Integer beeperId){
        JSONObject json = new JSONObject();
        try{
            Beeper beeper = beeperService.getById(beeperId);
            if(beeper == null || "".equals(beeper)) {
                json.put("message", "无该通知公告数据");
                json.put("data", "error");
            }else {
                beeperService.removeById(beeper);
                json.put("message", "该通知已删除！！");
                json.put("data", "success");
            }
        }catch (Exception e){
            json.put("state","error");
            json.put("message","系统异常，请查看系统日志");
        }

        return json.toString();
    }

    /**
     * 查看单条公告信息
     *
     * */
    @RequestMapping(value = "/SerchByBeeperId.do",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public String SerchByBeeperId(@RequestParam("beeperId") int beeperId, HttpSession session){
        JSONObject json = new JSONObject();
        try{
            UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            if (userInfo == null) {
                json.put("message", "用户不存在！");
                json.put("status", "error");
            }else {
                System.out.println("=================================");
                Beeper beeper = beeperService.getById(beeperId);
                if(beeper == null || "".equals(beeper)) {
                    json.put("message", "当前公告信息有误");
                }else {
                    //添加点击数进入通知公告模板
                    int clickCounts = beeperService.getById(beeperId).getClickCount();
                    beeper.setClickCount(clickCounts+1);
                    //添加已阅人id
                    String readers = beeperService.getById(beeperId).getReaders();
                    if(readers == null || "".equals(readers)) {
                        beeper.setReaders(userInfo.getUserId().toString());
                    }else {
                        String[] sb = readers.split(",");
                        boolean inof = false;
                        for(int i=0;i<sb.length;i++) {
                            int readerId = Integer.parseInt(sb[i]);
                            if(userInfo.getUserId() == readerId) {
                                inof = true;
                            }
                        }
                        if(inof = true ) {
                            System.out.println("该人员已阅 ，无需添加到已阅人员id串");
                        }else {
                            beeper.setReaders(readers+","+userInfo.getUserId().toString());
                        }
                    }
                    json.put("state","success");
                    json.put("message", "获取数据成功");
                    json.put("data", beeper);
                }
            }
        }catch (Exception e){
            json.put("state","error");
            json.put("message","系统异常，请查看系统日志");
        }

        return json.toString();
    }




    /**
     * 查询所有公告publish:all   查询所有未发布公告:publish :0  查询所有已发布公告 publish :1  查询所有已暂停公告 publish :2
     *
     * */
    @RequestMapping(value = "/findList.do",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public String findList(@RequestParam("publish") String publish) {
        JSONObject json = new JSONObject();
        try{
            List<Beeper> beepers = beeperService.findListByPublish(publish);
            json.put("data", beepers);
            json.put("message", "获取通知公告数据成功");
            json.put("state", "success");
        }catch (Exception e) {
            json.put("state","error");
            json.put("message","系统异常，请查看系统日志");
        }
        return json.toString();
    }

    @RequestMapping(value = "/finAll.do",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public String finAll(){
        JSONObject jsonObject = new JSONObject();
        try {
            List<Beeper> beepers = beeperService.list();
            jsonObject.put("data", beepers);
            jsonObject.put("state", "success");
        }catch (Exception e){
            jsonObject.put("state","error");
            jsonObject.put("message","系统异常，请查看系统日志");
        }
        return jsonObject.toString();
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除数据")
    @ApiImplicitParam(name="用户ids",value = "用户主键id Array",paramType = "delete",required = true,dataType = "int")
    @RequestMapping(value = "/deleteBeeperByIds", method= RequestMethod.POST)
    public Result deleteBeeper(@RequestParam("ids") List<Integer> ids){
        if (CollectionUtils.isEmpty(ids)) {
            return Result.fail("ids is null!");
        }

        if (beeperService.removeByIds(ids)) {
            return Result.success();
        }

        return Result.fail();
    }

    /**
     * 修改
     */
    @ApiOperation(value = "更新数据")
    @ApiImplicitParam(name="用户ids",value = "用户主键id Array",paramType = "update",required = true,dataType = "object")
    @RequestMapping(value = "/updateBeeperById", method = RequestMethod.POST)
    public Result update(@RequestBody Beeper beeper){
        if (null == beeper ||  0 == beeper.getBeeperId().intValue()) {
            return Result.fail("obj is null!");
        }

        if (beeperService.updateById(beeper)) {
            return Result.success();
        }

        return Result.fail();
     }

}
